package com.by.service.impl;

import com.by.bean.*;
import com.by.context.UserContext;
import com.by.core.utils.Assert;
import com.by.enums.BusinessMsg;
import com.by.mapper.GoodsMapper;
import com.by.mapper.SkuMapper;
import com.by.mapper.SkuStockMapper;
import com.by.mapper.SpuDetailMapper;
import com.by.msg.Constant;
import com.by.service.GoodsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.BatchResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    SpuDetailMapper spuDetailMapper;

    @Autowired
    SkuMapper skuMapper;

    @Autowired
    SkuStockMapper skuStockMapper;

    @Transactional
    @Override
    public int save(Spu spu) {
        //获取用户信息
        UserInfo info = UserContext.get();
        UserContext.clear();

        //保存SPU
        spu.setShopId(info.getShopId());
        spu.setShopCategoryId(info.getShopCategoryId());
        int rs = goodsMapper.insert(spu);
        Assert.isZero(rs, Constant.SAVE_SPU_FAIL);

        //保存明细
        SpuDetail detail = new SpuDetail()
                .setDetail(spu.getDetail())
                .setSpu_id(spu.getSpuId());
        rs = spuDetailMapper.insert(detail);
        Assert.isZero(rs, Constant.SAVE_SPU_DETAIL_FAIL);

        int total=0;

        //保存sku
        if (null != spu.getSkuList() && spu.getSkuList().size() > 0) {
            //遍历
            spu.getSkuList().forEach(el -> {
                el.setSpuId(spu.getSpuId());
                //保存sku
                int tmp=skuMapper.insert(el);
                Assert.isZero(tmp,Constant.SAVE_SKU_FAIL);

                //保存sku库存
                SkuStock skuStock=new SkuStock()
                        .setStock(el.getStock())
                        .setActualStock(el.getStock());
                tmp=skuStockMapper.insert(skuStock);
                Assert.isZero(tmp,Constant.SAVE_SKU_STOCK_FAIL);

              //total+=el.getStock()
            });

        }

        //保存spu库存

        //保存规格 获取规格 id

        //遍历保存归格值

        //保存规格值  获取id
        //保存spu attr 属性值


        return 0;
    }


}
